package com.nondo.rdp.finance.endpoint.api.app.course;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.nondo.rdp.auth.common.UserUtils;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.endpoint.model.ConvertCall;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.auth.endpoint.model.Query;
import com.nondo.rdp.core.common.AliyunVideoTool;
import com.nondo.rdp.core.common.BeanUtils;
import com.nondo.rdp.core.common.CommUtil;
import com.nondo.rdp.core.common.StatusConstant;
import com.nondo.rdp.core.common.ValidateUtil;
import com.nondo.rdp.core.model.AttachBean;
import com.nondo.rdp.core.model.Video;
import com.nondo.rdp.core.model.View;
import com.nondo.rdp.finance.domain.course.Course;
import com.nondo.rdp.finance.domain.course.Section;
import com.nondo.rdp.finance.domain.course.SectionComment;
import com.nondo.rdp.finance.domain.course.SectionProcess;
import com.nondo.rdp.finance.model.course.SectionBean;
import com.nondo.rdp.finance.model.course.SectionCommentBean;
import com.nondo.rdp.finance.model.course.SectionProcessQuery;
import com.nondo.rdp.finance.model.course.SectionQuery;
import com.nondo.rdp.finance.service.SettingService;
import com.nondo.rdp.finance.service.course.CourseBuyService;
import com.nondo.rdp.finance.service.course.CourseService;
import com.nondo.rdp.finance.service.course.SectionCommentService;
import com.nondo.rdp.finance.service.course.SectionProcessService;
import com.nondo.rdp.finance.service.course.SectionService;

@RestController("apiAppSection")
@RequestMapping("/api/app/section")
public class SectionEndpoint {
	
	@Autowired
    CommUtil commUtil;
	
	@Autowired
	AliyunVideoTool aliyunVideoTool;
	
    @Autowired
    SectionService sectionService;
    
    @Autowired
    CourseService courseService;
    
    @Autowired
    CourseBuyService courseBuyService;
    
    @Autowired
    SectionCommentService sectionCommentService;
    
    @Autowired
    SectionProcessService sectionProcessService;
    
    @Autowired
    SettingService settingService;

    @RequestMapping("/info/{id}")
    public View<SectionBean> info(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View<SectionBean> view = new View<SectionBean>(20000, "获取数据成功");

        Section section = null;
        SectionBean sectionBean = new SectionBean();
		if (id != null) {
			User user = UserUtils.getUser(request, response);
			section = sectionService.findOne(id);
			if (section == null) {
				return View.ofError("课节不存在");
			}
			Course course = section.getCourse();
			int isFree = course.getFree();
			if (isFree == 0) {
				int isBuy = courseBuyService.getOne(course.getId(), user.getId());
				if (isBuy == 0) {
					view.setCode(30000);
					view.setMessage("对不起，你没有购买该课程");
					return view;
				}
			}
			section.setReadNum(section.getReadNum() + 1);
			this.sectionService.updateApp(section,user);
			
			sectionBean = sectionService.getSectionDetail(section);
			
			AttachBean attachBean = sectionBean.getAttach();
			if (attachBean.getType() == 1) {
				attachBean.setPath(commUtil.getAudioUrl(attachBean.getPath()));
				sectionBean.setAttach(attachBean);
			}
			
			sectionBean.setCid(course.getId());

		}
        
        view.setData(sectionBean);
        
        return view;
    }

    @RequestMapping("/list")
    public View<Page<SectionQuery>> list(HttpServletRequest request, HttpServletResponse response, @RequestBody Query<Section> query) {
        View<Page<SectionQuery>> view = new View<Page<SectionQuery>>(20000, "获取列表成功");

        Section section = query.getData();
        
        User user = UserUtils.checkUser();
        
        Page<Section> page = sectionService.findAll(new Page<Section>(query.getPage(), query.getSize()), section);
        
        Page<SectionQuery> resultPage = page.convertPage(new ConvertCall<Section,Page<SectionQuery>>(){

			@Override
			public Page<SectionQuery> execute(Page<Section> srcPage) {
				Page<SectionQuery> sectionQueryListPage = new Page<SectionQuery>(srcPage.getPageNumber(), srcPage.getPageSize(), srcPage.getTotalPages(), srcPage.getTotalElements());
				List<Section> sectionList = srcPage.getContent();
				List<SectionQuery> sectionQueryList = new ArrayList<SectionQuery>();
				for(Section section : sectionList) {
					SectionQuery sectionQuery = SectionQuery.covert2Bean(section);
					if (user != null && user.getId() != null) {
						SectionProcess sectionProcess = null;
						sectionProcess = sectionProcessService.getOne(section.getId(), user.getId());
						if (sectionProcess != null) {
							sectionQuery.setPlayState(sectionProcess.getPlayState());
						}
					}
					sectionQueryList.add(sectionQuery);
				}
				sectionQueryListPage.setContent(sectionQueryList);
				return sectionQueryListPage;
			}
        	
        });

        view.setData(resultPage);

        return view;
    }

    @RequestMapping("/comment")
    public View<SectionCommentBean> comment(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody SectionCommentBean sectionComment) {
		View<SectionCommentBean> view = new View<SectionCommentBean>(20000, "评论成功");
		User user = UserUtils.getUser(request, response);
		SectionComment comment = new SectionComment();
		BeanUtils.copy(sectionComment, comment);
		Section section = this.sectionService.findOne(sectionComment.getSectionId());
		comment.setUser(user);
		comment.setSection(section);
		this.sectionCommentService.save(comment);
		sectionComment = SectionCommentBean.covert2Bean(comment);
		view.setData(sectionComment);
		return view;
    }
    
    @RequestMapping("/author/comment")
    public View<SectionCommentBean> authorComment(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody SectionCommentBean sectionComment) {
		View<SectionCommentBean> view = new View<SectionCommentBean>(20000, "评论成功");
		User user = UserUtils.getUser(request, response);
		SectionComment comment = this.sectionCommentService.findOne(sectionComment.getId());
		if (!user.getId().equals(comment.getSection().getPublisher().getId())) {
			return View.ofError("对不起，你没有权限进行操作");
		}
		comment.setAuthorCommentDate(new Date());
		comment.setAuthorComment(sectionComment.getAuthorComment());
		this.sectionCommentService.update(comment);
		sectionComment = SectionCommentBean.covert2Bean(comment);
		view.setData(sectionComment);
		return view;
    }
    
    
    @RequestMapping("/process/save")
    public View<SectionProcessQuery> processSave(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody SectionProcessQuery sectionProcessQuery) {
		View<SectionProcessQuery> view = new View<SectionProcessQuery>(20000, "保存成功");
		User user = UserUtils.getUser(request, response);
		SectionProcess sectionProcess = new SectionProcess();
		sectionProcess.setUser(user);
		Section section = sectionService.findOne(sectionProcessQuery.getSid());
		sectionProcess.setSection(section);
		sectionProcess.setTimePoint(sectionProcessQuery.getTimePoint());
		sectionProcess.setDuration(sectionProcessQuery.getDuration());
		Course course = section.getCourse();
		sectionProcess.setCourseId(course.getId());
		this.sectionProcessService.save(sectionProcess);
		return view;
    }
    
    @RequestMapping("/play/list")
    public View<Page<SectionProcessQuery>> playList(HttpServletRequest request, HttpServletResponse response, @RequestBody Query<SectionProcess> query) {
        View<Page<SectionProcessQuery>> view = new View<Page<SectionProcessQuery>>(20000, "获取列表成功");

        SectionProcess sectionProcess = query.getData();
        
        if(sectionProcess == null || sectionProcess.getCourseId() == null) {
        	return View.ofError("必须传入课程ID");
        }
        sectionProcess.setCourseId(sectionProcess.getCourseId());
        
        User user = UserUtils.getUser(request, response);
        sectionProcess.setUser(user);

        Page<SectionProcess> page = sectionProcessService.findAll(new Page<SectionProcess>(query.getPage(), query.getSize()), sectionProcess);
        
        Page<SectionProcessQuery> resultPage = page.convertPage(new ConvertCall<SectionProcess,Page<SectionProcessQuery>>(){

			@Override
			public Page<SectionProcessQuery> execute(Page<SectionProcess> srcPage) {
				Page<SectionProcessQuery> sectionProcessQueryPage = new Page<SectionProcessQuery>(srcPage.getPageNumber(), srcPage.getPageSize(), srcPage.getTotalPages(), srcPage.getTotalElements());
				List<SectionProcess> sectionList = srcPage.getContent();
				List<SectionProcessQuery> sectionProcessQueryList = new ArrayList<SectionProcessQuery>();
				for(SectionProcess sectionProcess : sectionList) {
					SectionProcessQuery sectionProcessQuery = SectionProcessQuery.covert2Bean(sectionProcess);
					sectionProcessQueryList.add(sectionProcessQuery);
				}
				sectionProcessQueryPage.setContent(sectionProcessQueryList);
				return sectionProcessQueryPage;
			}
        	
        });

        view.setData(resultPage);

        return view;
    }
    
    @RequestMapping("/process/get/{id}")
    public View<SectionProcessQuery> getOne(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
		View<SectionProcessQuery> view = new View<SectionProcessQuery>(20000, "获取成功");
		User user = UserUtils.getUser(request, response);
		SectionProcess sectionProcess = sectionProcessService.findOne(id);
		if (!user.getId().equals(sectionProcess.getUser().getId())) {
			view.setCode(50000);
			view.setMessage("对不起，你没有权限进行操作");
			return view;
		}
		SectionProcessQuery sectionProcessQuery = SectionProcessQuery.covert2Bean(sectionProcess);
		view.setData(sectionProcessQuery);
		return view;
    }

	@RequestMapping(value = "/play/auth")
	public View<GetVideoPlayAuthResponse> playAuth(HttpServletRequest request,
			HttpServletResponse response, @RequestBody Video video, BindingResult result) {
		View<GetVideoPlayAuthResponse> view = new View<GetVideoPlayAuthResponse>(
				20000, "授权成功");
		if (result.hasErrors()) {
			view.setCode(40000);
			view.setMessage(ValidateUtil.first(result.getAllErrors()));
			return view;
		}
		Section section = sectionService.findOne(video.getSid());
		if (!video.getVideoId().equals(section.getAttach().getVideoId())) {
			return View.ofError("对不起，该课程ID和视频ID不匹配");
		}
		
		Course course = section.getCourse();
		int isFree = course.getFree();
		
		if (isFree == 0) {
			String isHide = settingService.isHideBuyButton(video.getVno());
			if (isHide.equals(StatusConstant.SHOW_BUY_BUTTON)) {
				User user = UserUtils.checkUser();
				if (user == null || user.getId() == null) {
					view.setCode(40001);
					view.setMessage("对不起，请先登录");
					return view;
				}
				int isBuy = courseBuyService.getOne(course.getId(), user.getId());
				if (isBuy == 0) {
					view.setCode(30000);
					view.setMessage("对不起，你没有订阅该课程");
					return view;
				}
			}
		}
		try {
			GetVideoPlayAuthResponse authResponse = aliyunVideoTool
					.getVideoPlayAuth(video.getVideoId());
			view.setData(authResponse);
		} catch (ClientException e) {
			return View.ofError("获取播放凭证失败");
		}
		return view;
	}
    
}
